use crate::security::stock::balance_sheet;
use crate::security::stock::{FinanceReport, FinanceReportItem};

use crate::security::stock::balance_sheet::FinanceReportType;
use bytes::Bytes;
use encoding::all::{GBK, UTF_8};
use encoding::{DecoderTrap, Encoding};
use serde::{Deserialize, Serialize};
use crate::security::stock::quote::HistoricalStockQuote;

pub async fn get_finance_report(
    stock_code: &str,
    report_type: &FinanceReportType,
) -> anyhow::Result<FinanceReport> {
    balance_sheet::load(stock_code, report_type).await
}

pub async fn search(word: &str, count: usize) -> Vec<StockItem> {
    let url = format!("http://quotes.money.163.com/stocksearch/json.do?type=&count={}&word={}&t=0.14336006599069717",
                      count, word);
    let resp = crate::util::http::get(url.as_str()).await.unwrap();
    parse(&resp.data)
}

pub async fn quote_price(code: &str) -> Vec<HistoricalStockQuote>{
     crate::security::stock::service::get_stock_quote(code, None, None).await.unwrap()
}

fn parse(data: &Bytes) -> Vec<StockItem> {
    let data = String::from_utf8_lossy(data.as_ref());
    // _ntes_stocksearch_callback(
    let mut data = data.replacen("_ntes_stocksearch_callback(", "", 1);
    let data = &data.as_str()[0..data.len() - 1];
    println!("data is {}", data);
    serde_json::from_str::<Vec<StockItem>>(data).unwrap()
}

#[derive(Serialize, Deserialize)]
pub struct StockItem {
    pub code: String,
    #[serde(rename(deserialize = "type"))]
    pub type_: String,
    pub symbol: String,
    pub tag: String,
    pub spell: String,
    pub name: String,
}
